package com.wf.smartcomm.server.admin.action;

import java.io.File;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.aspectj.util.FileUtil;
import org.json.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ModelDriven;
import com.wf.smartcomm.server.apns.IApnsService;
import com.wf.smartcomm.server.apns.model.Payload;
import com.wf.smartcomm.server.bean.Announcement;
import com.wf.smartcomm.server.bean.Image;
import com.wf.smartcomm.server.bean.ThumbImage;
import com.wf.smartcomm.server.bean.UnitMachine;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.model.PushMessage;
import com.wf.smartcomm.server.push.Pusher;
import com.wf.smartcomm.server.service.AnnounceService;
import com.wf.smartcomm.server.service.ImageService;
import com.wf.smartcomm.server.service.ThumbImageService;
import com.wf.smartcomm.server.service.UnitMachService;
import com.wf.smartcomm.server.service.UserService;
import com.wf.smartcomm.server.util.ConstantUtils;
import com.wf.smartcomm.server.util.IdUtils;
import com.wf.smartcomm.server.util.ImageUtils;
import com.wf.smartcomm.server.util.PushUtils;
import com.wf.smartcomm.server.util.StringUtil;

@Controller("adminAnnounce")
@Scope("prototype")
public class AnnounceAction extends BaseAction implements ModelDriven<Announcement>{

	private Announcement announce = new Announcement();
	@Resource
	private AnnounceService announceServiceImpl;
	
	@Resource
	private UserService userServiceImpl;
	
	@Resource
	private UnitMachService unitMachService;
	
	private List<File> upload;  
    // /多个上传文件的类型集合  
    private List<String> uploadContentType;  
   // 多个上传文件的文件名集合  
    private List<String> uploadFileName;  
    
	public List<File> getUpload() {
		return upload;
	}

	public void setUpload(List<File> upload) {
		this.upload = upload;
	}

	public List<String> getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(List<String> uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public List<String> getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(List<String> uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public void add() throws Exception{
		User user = (User) session.getAttribute("loginUser");
		announce.setUser(user);
		announce.setVillage(user.getLoginVillage());
		
		if (upload != null && upload.size() > 0) {
			for (File file : upload) {
				String fileName = IdUtils.uuid()+".png";
				String path = request.getServletContext().getRealPath(
						"images");
				String url = "http://"+PushUtils.pushConfig.getProperty("ImageServerIp");
				if (request.getServerPort() != 80) {
					url+=":"+request.getServerPort();
				}
				url+=request.getContextPath()+"/images/";
				announce.setImageUrl(url+fileName);
				File des = new File(path + File.separator + fileName);
				FileUtil.copyFile(file, des);
				
				ImageUtils.getThumbnail(des.getAbsolutePath(),
						request.getServletContext().getRealPath(
								"thumbImages")+File.separator+fileName, 150, 100);
			}
		
		}
		if (!StringUtil.isEmpty(announce.getObjectId())) {
			if (StringUtil.isEmpty(announce.getImageUrl())) {
				announce.setImageUrl(announceServiceImpl.get(announce.getObjectId()).getImageUrl());
			}
			announce.setCreatedAt(String.valueOf(System.currentTimeMillis()));
			announceServiceImpl.update(announce);
		}else {
			announceServiceImpl.save(announce);
		}
		printJsonData(200);
		Pusher pusher = PushUtils.getInstance();
		PushMessage msg = new PushMessage();
		msg.setPushType(ConstantUtils.PUSH_TYPE_ANNOUNCE_MSG);
		msg.setData(announce.getObjectId());
		unitMachService.listAllByVillage(user.getLoginVillage(), page);
		List<UnitMachine> unitMachines = (List<UnitMachine>) page.getDataList();
		for (UnitMachine unitMachine : unitMachines) {
			pusher.push0x20Message(unitMachine.getPushId().getBytes(), outGson.toJson(msg).getBytes());
		}
		pusher.close();
		userServiceImpl.listByVillage(user.getLoginVillage(), page);
		Pusher clientPusher = PushUtils.getClientPusher();
		IApnsService service = PushUtils.getApnsService();
		List<User> users = (List<User>) page.getDataList();
		for (User u : users) {
			if (u.getDeviceType().equals(ConstantUtils.DEVICE_TYPE_ANDROID)) {
				clientPusher.push0x20Message(u.getPushId().getBytes(), outGson.toJson(msg).getBytes());
			} else if(u.getDeviceType().equals(ConstantUtils.DEVICE_TYPE_APPLE)){
				Payload payload = new Payload();
				payload.setAlert(announce.getSubject());
				payload.setBadge(0);
				payload.setSound("default");
				payload.addParam("objectId", announce.getObjectId());
				payload.addParam("type", ConstantUtils.PUSH_TYPE_ANNOUNCE_MSG);
				service.sendNotification(u.getAppleToken(), payload);
			}
		}
		clientPusher.close();
	}
	
	public void list() throws Exception {
		String aoData = request.getParameter("aoData");
		String sEcho = "";
		String iDisplayStart = "";
		String iDisplayLength = "";
		String sSearch = "";
		User user = (User) session.getAttribute("loginUser");
		JSONObject jo = new JSONObject(aoData);
		sEcho = jo.getString("sEcho");
		iDisplayStart = jo.getString("iDisplayStart");
		iDisplayLength = jo.getString("iDisplayLength");
		sSearch = jo.getString("sSearch");
		page.setBeginIndex(Integer.parseInt(iDisplayStart));
		page.setPageSize(Integer.parseInt(iDisplayLength));
		announceServiceImpl.list(user.getLoginVillage(), page);
		
		int  initEcho = Integer.parseInt(sEcho)+1;
		int count = page.getTotalCount();
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("iTotalRecords", count);
		dataMap.put("sEcho",initEcho);
		dataMap.put("iTotalDisplayRecords", count);
		dataMap.put("aaData", page.getDataList());
		printJsonData(outGson.toJson(dataMap));
	}
	
	public void delete() throws Exception{
		announceServiceImpl.delete(announce);
		printJsonData(200);
	}
	
/*     */   public String edit() throws Exception {
/* 165 */     this.announce = this.announceServiceImpl.get(this.announce.getObjectId());
			  //announce.setContent(URLDecoder.decode(announce.getContent(), "UTF-8"));
/* 172 */     this.request.setAttribute("announce", announce);
/* 173 */     return "edit";
/*     */   }
	
	@Override
	public Announcement getModel() {
		// TODO Auto-generated method stub
		return announce;
	}
	
}
